﻿using WeskyQuantDemo.Models.Basics;

namespace WeskyQuantDemo.Services.BasicServices
{
    /// <summary>
    /// 基础指标
    /// </summary>
    public class BasicIndicators
    {
        /// <summary>
        /// 计算ema
        /// </summary>
        /// <param name="input">需要计算的数据集合</param>
        /// <param name="period">天数</param>
        /// <returns></returns>
        public static EmaResult CalculateEMA(IEnumerable<double> input, int period)
        {
            var returnValues = new List<double>();
            double multiplier = 2.0 / (period + 1); // 确保进行浮点数计算
            double initialSMA = input.Take(period).Average();

            returnValues.Add(initialSMA);

            var copyInputValues = input.ToList();

            // 从index=period开始，因为我们已经计算了第一个EMA值为initial SMA
            for (int i = period; i < copyInputValues.Count; i++)
            {
                double lastEMA = returnValues.Last(); // 获取上一个EMA值
                double newEMA = (copyInputValues[i] - lastEMA) * multiplier + lastEMA;
                returnValues.Add(newEMA);
            }

            var result = new EmaResult()
            {
                Values = returnValues,
                StartIndexOffset = period - 1
            };

            return result;

        }

    }
}
